import socket
import coder
import pygame
import time

address = "192.168.10.160"
port = 5000
moveAix = 1
rotateAix = 3
interval = 0.1
deadZone = 0.01

s=socket.socket()

while(True):
    try:
        print("try connect to server...")
        s.connect((address,port))
        break
    except:
        time.sleep(1)

print("connecting to "+address+':'+str(port))

pygame.init()
pygame.joystick.init()
jsCount = pygame.joystick.get_count()
js=False
if(jsCount==0):
    print("Non joystick found")
    #exit()
else:
    js = pygame.joystick.Joystick(0)
    js.init()

size = (200, 200)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Input window")

exit=False
while(not exit):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit = True
    pygame.display.update()

    move = 0
    rotate = 0
    if(js!=False):
        move = -js.get_axis(moveAix)
        rotate = -js.get_axis(rotateAix)
    else:
        buttons = pygame.key.get_pressed()
        move = int(buttons[pygame.K_w])-int(buttons[pygame.K_s])
        rotate = int(buttons[pygame.K_a])-int(buttons[pygame.K_d])
    #print("move:"+str(move)+':rotate'+str(rotate))
    #if(abs(move) < deadZone and abs(rotate) < deadZone):
    #    continue
    input = {'move':move,'rotate':rotate}
    bytes = coder.EncoderWrite(input).encode()
    try:
        s.send(bytes)
        print("move:"+str(move)+':rotate'+str(rotate))
    except:
        s.close()
        print("Send fail,maybe server close")
        exit()
    time.sleep(interval)
